package com.alog.yzd.bookmall.dao.cart;

import com.alog.yzd.bookmall.domain.book.Book;
import com.alog.yzd.bookmall.domain.cart.CartItem;
import com.alog.yzd.bookmall.domain.user.User;
import com.alog.yzd.bookmall.utils.jdbc.TxQueryRunner;
import com.alog.yzd.commons.CommonUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class CartDao {
    QueryRunner qr = new TxQueryRunner();

    /**
     * 查询多个CartItem
     * @param cartItemIds
     * @return
     * @throws SQLException
     */
    public List<CartItem> loadCartItems(String cartItemIds) throws SQLException {
        Object[] ids = cartItemIds.split(",");
        String wheresql = toWhereSql(ids.length);
        String sql = "select * from t_cartitem c , t_book b where c.bid = b.bid and " + wheresql;
        List<Map<String, Object>> mapList = qr.query(sql, new MapListHandler(), ids);
        List<CartItem> cartItems = toCartItemList(mapList);
        return cartItems;
    }

    /**
     * 按Id查询
     * @param cartItemId
     * @return
     * @throws SQLException
     */
    public CartItem findByCartItemId(String cartItemId) throws SQLException {
        String sql = "select * from t_cartitem c, t_book b where c.cartItemId = ? and c.bid = b.bid";
        Map<String, Object> map = qr.query(sql, new MapHandler(), new Object[]{cartItemId});
        CartItem cartItem = toCartItem(map);
        return cartItem;
    }

    /**
     * 生成Where子句
     * @param len
     * @return
     */
    private String toWhereSql(int len){
        StringBuilder sb = new StringBuilder("cartItemId in(");
        for(int i = 0 ; i < len; i++){
            if(i == len - 1){
                sb.append("?)");
            } else {
                sb.append("?,");
            }
        }
        return sb.toString();
    }

    /**
     * 批量删除购物车的条目
     * @param cartItemIds
     * @throws SQLException
     */
    public void batchDelete(String cartItemIds) throws SQLException {
        Object[] ids = cartItemIds.split(",");
        String wheresql = toWhereSql(ids.length);
        String sql = "delete from t_cartitem where " + wheresql;
        qr.update(sql, ids);
    }
    /**
     * 添加购物车条目
     * @param item
     * @throws SQLException
     */
    public void addCartItem(CartItem item) throws SQLException {
        String sql = "insert into t_cartitem(cartItemId, quantity, bid, uid) values(?,?,?,?)";
        qr.insert(sql, new ScalarHandler<>(), new Object[]{item.getCartItemId(),
                                                    item.getQuantity(),
                                                    item.getBook().getBid(),
                                                    item.getUser().getUid()});
    }

    /**
     * 修改指定条目的数量
     * @param cartItemId
     * @param quantity
     * @throws SQLException
     */
    public void updateQuantity(String cartItemId, String quantity) throws SQLException {
        String sql = "update t_cartitem set quantity = ? where cartItemId = ?";
        qr.update(sql, new Object[]{quantity, cartItemId});
    }

    /**
     * 通过UserId和BookId查询CartItem
     * @param uid
     * @param bid
     * @return
     * @throws SQLException
     */
    public CartItem findByUidAndBid(String uid, String bid) throws SQLException {
        String sql = "select * from t_cartitem where bid = ? and uid = ?";
        Map<String, Object> map = qr.query(sql, new MapHandler(), new Object[]{bid, uid});
        CartItem cartItem = toCartItem(map);
        return cartItem;
    }

    /**
     * 通过用户Id查询
     * @param uid
     * @return
     * @throws SQLException
     */
    public List<CartItem> findByUid(String uid) throws SQLException {
        String sql = "select * from t_cartitem c, t_book b where c.bid = b.bid and c.uid = ? order by c.orderBy";
        List<Map<String, Object>> mapList = qr.query(sql, new MapListHandler(), new Object[]{uid});
        List<CartItem> cartItems = toCartItemList(mapList);
        return cartItems;
    }

    /**
     * 将List<Map<String, Object>>映射成List<CartItem>
     * @param mapList
     * @return
     */
    private List<CartItem> toCartItemList(List<Map<String, Object>> mapList){
        List<CartItem> cartItems = new ArrayList<>();
        for(Map<String, Object> map : mapList){
            CartItem cartItem = toCartItem(map);
            cartItems.add(cartItem);
        }
        return cartItems;
    }
    /**
     * 将Map映射成CartItem
     * @param map
     * @return
     */
    private CartItem toCartItem(Map<String, Object> map){
        if(map == null || map.size() == 0){
            return null;
        }
        CartItem ci = CommonUtils.toBean(map, CartItem.class);
        Book book = CommonUtils.toBean(map, Book.class);
        User user = CommonUtils.toBean(map, User.class);
        ci.setBook(book);
        ci.setUser(user);
        return ci;
    }
}
